<?php 

$path = drupal_get_path('module', 'rules'); 
drupal_add_css($path . '/css/rules.css');
//drupal_add_js($path . '/js/rules.js');

function ruleshome(){

  global $base_url;
  global $language;
  $url = $base_url . '/' . drupal_get_path('module', 'rules');
 if($language->language=='ta'){
	$lang= 'ta';
 }else{
 	$lang='';
 }
 
  my_db_change(1);
  $query=db_query("SELECT DISTINCT(c.dep_id), c.dept_name as department_name   FROM
    node AS a, field_data_field_rules_dep AS b, depart_mst AS c,field_data_field_rules_avail as d 
    WHERE a.nid = d.entity_id AND a.nid= b.entity_id  AND d.field_rules_avail_value != '' AND  a.status = 1 
    AND c.dep_id =  CAST(b.field_rules_dep_value AS INT)  ORDER BY c.dept_name");
	
	$op = "<div class='document_head_list'>";
	$st =1;
	foreach($query as $dept){
		if($st%2!=0) { 
			$cls = "first_clm";
		} 
		else {
			$cls = "second_clm";
		}
	
		 $op .= "<div class='".$cls." d".$dept->dep_id."'>";
		 $op .= "<img src='".$url."/images/icon_main.png' alt='More' /> "; 
		 $op .= l(trim(t($dept->department_name)),$lang.'/rules/dept/'.$dept->dep_id)."</div>";	 
		 
		 $st++;
	}
	 $op .="</div>";
	$output .= get_rules_header('dept');	
	$output .= "<div class='result_inner'>";
	$output .= $op;
	$output .= "<div class='clr'></div></div>";	
	my_db_change(0);
  return $output;
}

/**
 * Function for rules_department()
 * @return string
 */
function rules_department(){
  global $base_url;
  global $language;
    $url = $base_url . '/' . drupal_get_path('module', 'rules');
 if($language->language=='ta'){
	$lang= '/ta';
 }else{
 	$lang='';
 }
 $output .= get_rules_header('dept');	
  $output .="<div class='result_inner'><div class='res_dept' ><span style='float:right;margin-right:23px;'>".l(t('Back'),'rules/dept')."</span></div>";
  $catid = arg(2);
	my_db_change(1);
	$query = new EntityFieldQuery();
	$query->entityCondition('entity_type', 'node')
	  ->entityCondition('bundle', 'rulesandregulation')   
	  ->fieldCondition('field_rules_dep', 'value', $catid, '=')
	  ->fieldOrderBy('field_rules_dep','value','ASC')
	  ->propertyCondition('status',1)
	 ->propertyCondition('language', array($GLOBALS['language']->language, LANGUAGE_NONE), 'IN');
	// ->pager(15,0); 
	  
	$result = $query->execute();	
	$nid = current($result['node']);
	
	if (isset($result['node'])) {
	  $news_items_nids = array_keys($result['node']); 	  
	  $items = entity_load('node', $news_items_nids);
	}
	my_db_change(0);
	$i=0;
//print "<pre>";print_r($items);print "</pre>";
	foreach($news_items_nids as $nid){
		my_db_change(1);
		$vid = db_query('SELECT vid FROM {node} WHERE nid = :nid', array(':nid' => $nid))->fetchField();
		$row = node_load($nid, $vid);
		my_db_change(0);
		if ($row->field_rules_dep['und'][0]['value'] != $curdept )	
		{
			$curdept = $row->field_rules_dep['und'][0]['value'];
			$output .= "<div class='res_dept' style='width:500px;margin-top:10px;margin-bottom:10px;'>
			 <span><strong>".t(dept_name($curdept))."</strong></span>
			</div>";
		}
	$icon ='<img alt="Download Icon" src="http://cms.tn.gov.in/sites/default/files/icons/pdf_icon.gif">';
	$link = $row->field_rules_fileup['und'][0]['uri'];
		$wrapper = file_stream_wrapper_get_instance_by_uri($link);
		if($wrapper == true){
			 $filepath = $wrapper->getDirectoryPath() . "/" . file_uri_target($link);
		}
	 $filepath="'http://cms.tn.gov.in/tncms_latest/$filepath'";
		if ($row->field_rules_fileup['und'][0]['filesize'] != '0') {
			$kb = ceil($row->field_rules_fileup['und'][0]['filesize']/1024);
			$kbyte= $kb.KB;
			if($kb >1024) { 
				$kb = ceil($kb/1024);
				$kbyte= $kb.MB;
			}
	    }	
$output .='<div><div class="res_title_ch"><p>
		<a href="javascript:void(0);" onClick="return tnportal_ext_window('.$filepath.');">'.ucfirst($row->title).$icon.'('.$kbyte.')</a></p></div>';
$i++;
}
if($i==0) { 
 $output.="<div class='no_record'>No Record Found </div>";
}
$output .="</div></div>";
return $output;
}

/**
 * Function rules_atoz()
 * @return Ambigous <An, string>
 */
function rules_atoz(){
global $language,$base_url;
$url = $base_url . '/' . drupal_get_path('module', 'rules');
$alp = arg(2);
 if($language->language=='ta'){
	$lang= '/ta';
 }else{
 	$lang='';
 }
	$output .= get_rules_header('atoz');
	$output .= "<div class='view-header'>" . AtoZ_letters($alp) . "</div>";
	$output .= "<div class='result_inner'>";
	$val= strtoupper($alp);	
	 
	 my_db_change(1);
		if($val != 'ALL'){
 
			$query = new EntityFieldQuery();
			$query->entityCondition('entity_type', 'node')
			  ->entityCondition('bundle', 'rulesandregulation')   
			  ->propertyCondition('status',1)
			  ->propertyCondition('title',$val.'%','LIKE')
			  ->propertyCondition('language', $language->language, '=')
			  ->propertyOrderBy('title','ASC')
			  ->pager(15,0); 
		 }
		 else {
 
			$query = new EntityFieldQuery();
			$query->entityCondition('entity_type', 'node')
			  ->entityCondition('bundle', 'rulesandregulation')   
			  ->propertyCondition('status',1)
			  ->propertyCondition('language', $language->language, '=')
			  ->propertyOrderBy('title','ASC')
			  ->pager(15,0); 
		 }
		$result = $query->execute();
	
	
	$nid = current($result['node']);
	
	if (isset($result['node'])) {
	  $news_items_nids = array_keys($result['node']); 	  
	  //$items = entity_load('node', $news_items_nids);
	}
	my_db_change(0);
foreach($news_items_nids as $nid){
	my_db_change(1);
	$vid = db_query('SELECT vid FROM {node} WHERE nid = :nid', array(':nid' => $nid))->fetchField();
	$row = node_load($nid, $vid);
	my_db_change(0);
		
	$icon ='<img alt="Download Icon" src="http://cms.tn.gov.in/sites/default/files/icons/pdf_icon.gif">';
	$link = $row->field_rules_fileup['und'][0]['uri'];		
		$wrapper = file_stream_wrapper_get_instance_by_uri($link);
		if($wrapper == true){
			 $filepath = $wrapper->getDirectoryPath() . "/" . file_uri_target($link);
		}
	 $filepath="'http://cms.tn.gov.in/tncms_latest/$filepath'";
		if ($row->field_rules_fileup['und'][0]['filesize'] != '0') {
			$kb = ceil($row->field_rules_fileup['und'][0]['filesize']/1024);
			$kbyte= $kb.KB;
			if($kb >1024) { 
				$kb = ceil($kb/1024);
				$kbyte= $kb.MB;
			}
	    }	
$output .='<div class="res_title_ch"><p>
		<a href="javascript:void(0);" onClick="return tnportal_ext_window('.$filepath.');">'.ucfirst($row->title).$icon.'('.$kbyte.')</a></p></div>';
$i++;
}
if($i==0) { 
 $output.="<div class='no_record'>No Record Found </div>";
}
$output .="</div>";
$output .= theme('pager');	

return $output;
}

/*
 * Function for rules_search_form()
 */
function rules_search_form(){
global $language,$base_url;
$url = $base_url . '/' . drupal_get_path('module', 'rules');
$alp = arg(2);
 if($language->language=='ta'){
	$lang= '/ta';
 }else{
 	$lang='';
 }
	$output .= get_rules_header('find');		
	$output .= '<div class="result_inner_search">'. drupal_render(drupal_get_form('rules_search'));
	return $output;

}

function rules_search($form_state){	
	$keyword = trim(arg(2));
		$form['rules_search'] = array(
		'#type' => 'textfield',
		'#title' => t('Keyword:'),
		'#default_value' => $keyword ? $keyword : '',
		'#size'=>'35',
	);  
	
    $form[ 'rules_submit' ] = array(
		'#title' => 'Submit', 
		'#type' => 'submit', 
		'#value' => 'Go', 
		'#name' => 'search',
		'#prefix' => '<div class="sea_go_bt">',
		'#suffix' => '</div>',
	
	);
	
	return $form;
	
}
function rules_search_submit($form,&$form_state){
	global $base_url;		 
	if ($form_state[clicked_button]['#name'] == 'search') {		
		$str = $form_state[values][rules_search];
		if(empty($str)) {
		form_set_error('rules_search','Please Enter Key Word');
		print 'Please Enter Key Word';
		}		
	}	
				
	$form_state['redirect'] = 'rules/search/'.$str; 
    return;
}

function get_rules_header($css){
	global $base_url;
/*	 if($css=='cate') { $cate_cls= "view_head_sel"; }else {$cate_cls='view_head_nonsel'; }*/
     if($css=='dept') { $dept_cls= "view_head_sel"; }else {$dept_cls='view_head_nonsel'; }
     if($css=='find') { $find_cls= "view_head_sel"; }else {$find_cls='view_head_nonsel'; }
	 if($css=='atoz') { $atoz_cls= "view_head_sel"; }else {$atoz_cls='view_head_nonsel'; }
	  
	   
	global $language;
	if($language->language=='ta'){
		$css='rules_ta';
		$lang='/ta'; 
		
	}
	else{
		$css='rules';
		$lang='';
	}
	
	$html = "<div class='view-header' id='viewmod_$css'>
				<div class='inner_tab_content'>
				<div class='inner_li'><a class='$dept_cls' href='$base_url$lang/rules/dept'>".t('Department wise')."</a></div>					
				<div class='inner_li'><a class='$find_cls' href='$base_url$lang/rules/search'>".t('Search')."</a></div>
				<div class='inner_li'><a class='$atoz_cls' href='$base_url$lang/rules/atoz'>".t('A to Z')."</a></div>
				<div class='clr'></div></div></div>";
	return $html;
}

/**
 * Function for rules_search_result_form()
 * @return Ambigous <An, string>
 */
function rules_search_result_form() {
global $language,$base_url;
$url = $base_url . '/' . drupal_get_path('module', 'rules');
$output = rules_search_form();
	$go_keyword= trim(arg(2));
	$go_keyword= strtolower($go_keyword);	
	//$ser_string = array();
	$go_keyword = preg_replace('/[\p{Z}\s]{2,}/u', ' ', $go_keyword);
 	$go_keyword=pg_escape_string($go_keyword); 
	
	$len = drupal_strlen($go_keyword);
	$keyword1 =$go_keyword; 
    // Do not count UTF-8 continuation bytes.
 if(!empty($keyword1)){
	$position[0]=strpos($keyword1,'"');
	 if($position[0] != "");{
		print  $position[1]=strpos($keyword1,'"',$position[0]+1);	
	  }
  }
 if(!empty($position[1]))
 {
	//echo substr($keyword,1)."</br>";
	$k=0;
	for($i=0;$i<=$len;$i++){	
	$position[0]=strpos($keyword1,'"');	
	if(strlen($keyword1) !=0)
	{
	if($position[0] !=0 && $position[0] !="")
	$str_not_quote[$k++] =substr($keyword1,0,$position[0]);
	if($position[0] ==false)
	$str_not_quote[$k++] =substr($keyword1,0,strlen($keyword1));
	}
	
	
	 $position[1]=strpos($keyword1,'"',$position[0]+1);
	
	 if(empty($position[1]))
	 {
	 break;
	 }
	 $sub_string_len = $position[1] - $position[0]-1;
	 
 $ser_string[$i] = substr($keyword1,$position[0]+1, $sub_string_len);
	
	 $part_string= substr($keyword1,$position[1]+1, $len);
	
	$keyword1 =trim($part_string);
	if(empty($keyword1))
	{
	break;
	}
	}
	}
	$ser_string = array_filter_customize($ser_string);
	//print_r($ser_string);
	if(!empty($ser_string))
	{
	
		$sql_search_clause = search_keyword('LOWER(n.title)', $ser_string, $str_not_quote);
	}
	
	$go_val = $go_keyword; 
	my_db_change(1);
	$query = new EntityFieldQuery();
	$query->entityCondition('entity_type', 'node')
		  ->entityCondition('bundle', 'rulesandregulation')   
		  ->propertyCondition('status',1)
		  ->propertyCondition('title',$go_val.'%','LIKE')
		  ->propertyOrderBy('title','ASC')
		  ->pager(25,0); 
	$result = $query->execute();	
	$nid = current($result['node']);
	
	if (isset($result['node'])) {
	  $news_items_nids = array_keys($result['node']); 	  
	  //$items = entity_load('node', $news_items_nids);
	}
	my_db_change(0);
	foreach($news_items_nids as $nid){
		my_db_change(1);
		$vid = db_query('SELECT vid FROM {node} WHERE nid = :nid', array(':nid' => $nid))->fetchField();
		$row = node_load($nid, $vid);
		my_db_change(0);
		
	$icon ='<img alt="Download Icon" src="http://cms.tn.gov.in/sites/default/files/icons/pdf_icon.gif">';
	$link = $row->field_rules_fileup['und'][0]['uri'];		
		$wrapper = file_stream_wrapper_get_instance_by_uri($link);
		if($wrapper == true){
			 $filepath = $wrapper->getDirectoryPath() . "/" . file_uri_target($link);
		}
	 $filepath="'http://cms.tn.gov.in/tncms_latest/$filepath'";
		if ($row->field_rules_fileup['und'][0]['filesize'] != '0') {
			$kb = ceil($row->field_rules_fileup['und'][0]['filesize']/1024);
			$kbyte= $kb.KB;
			if($kb >1024) { 
				$kb = ceil($kb/1024);
				$kbyte= $kb.MB;
			}
	    }	
$output .='<div class="res_title_ch"><p>
		<a href="javascript:void(0);" onClick="return tnportal_ext_window('.$filepath.');">'.ucfirst($row->title).$icon.'('.$kbyte.')</a></p></div>';
$i++;
}
if($i==0) { 
 $output.="<div class='no_record'>No Record Found </div>";
}
	$output .= '</div>';
	$output .= theme('pager');	
	my_db_change(0);
	return $output;

}

function AtoZ_letters($alp){
	global $base_url;
		//print_r( strtolower($alpha ));
	for($i =65; $i < 91; $i++){
			$class = "";
	
// strtolower($val );
		if(chr($i) == $alp){
			$class = " view_head_sel";
		}
		else
		{
			$class = " ";
		}
		//$linkOp .= l($val,'rules/atoz/'.$val,array('attributes'=>array('class'=>$class)))."&nbsp;&nbsp;";
		 $linkOp .= '<a class = "myclass' . $class . '"  href = "' .$base_url.'/rules/atoz/'. chr($i) .'" >' . chr($i) . '</a>';
	}
	$class = "";
	if($alp == 'All'){
		$class = " view_head_sel";
	}
	$linkOp .= '<a class = "myclass' . $class . '" href = "' .$base_url.'/rules/atoz/All" title = "All" id = "All"> All </a>';
	$StrOp = "<div class='result_inner_atoz'>";
	$StrEnd = "</div>";
	$Grey = "<div class='grey_bord_line'></div>";//$linkOp .="<br /><br />";
	return $StrOp . $linkOp . $Grey . $StrEnd;
}